//
//  SQLiteDataBaseManager.m
//  通讯录
//
//  Created by mafeng on 16/8/8.
//  Copyright © 2016年 mafeng. All rights reserved.
//

#import "SQLiteDataBaseManager.h"
#import "Contact.h"
@implementation SQLiteDataBaseManager
+ (SQLiteDataBaseManager *)shareManager {
    
    static SQLiteDataBaseManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[SQLiteDataBaseManager alloc] init];
    });
    return manager;
}

- (BOOL)isOperationResult:(int)result alertText:(NSString *)text {
    BOOL isOperation = YES;
    if (result == SQLITE_OK) {
        isOperation = YES;
        NSLog(@"%@成功", text);
    } else {
        NSLog(@"%@失败, 错误码是%d", text, result);
        isOperation = NO;
    }
    return isOperation;
}

- (BOOL)openSQLite3 {
    NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *document = [pathArray firstObject];
    NSString *dbPath = [document stringByAppendingPathComponent:@"contact.db"];
    int result = sqlite3_open([dbPath UTF8String], &dbPoint);
    return [self isOperationResult:result alertText:@"打开数据库"];
}

- (BOOL)closeSQLite3 {
    int result = sqlite3_close(dbPoint);
    return [self isOperationResult:result alertText:@"关闭数据库"];
}

- (BOOL)createTable {
    NSString *createSQL = @"create table contact (contact_id integer primary key autoincrement contact_name text contact_age text contact_phoneNumber text contact_gender text)";
    int result = sqlite3_exec(dbPoint, [createSQL UTF8String], NULL, NULL, NULL);
    return [self isOperationResult:result alertText:@"创建表"];
}

- (BOOL)insertContact:(Contact *)contact {
    NSString *insertSQL = [NSString stringWithFormat:@"INSERT into contact (contact_id, contact_name, contact_age, contact_gender, contact_phoneNumber, contact_headImageData) values (null, %@, %@, %@, %@, %@)", contact.name, contact.age, contact.gender, contact.phoneNumber, contact.headImageData];
    int result = sqlite3_exec(dbPoint, [insertSQL UTF8String], NULL, NULL, NULL);
    return [self isOperationResult:result alertText:@"插入数据"];
}

- (NSArray *)selectAll {
    NSString *selectAll = @"select *from contact";
    // 替身指针
    sqlite3_stmt *stmt = NULL;
    int result = sqlite3_prepare(dbPoint, [selectAll UTF8String], -1, &stmt, NULL);
    NSMutableArray *array = [NSMutableArray array];
    // 如果查询结果成功
    if (result == SQLITE_OK) {
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            int contact_id = sqlite3_column_int(stmt, 0);
            const unsigned char * contact_name = sqlite3_column_text(stmt, 1);
            const unsigned char * contact_sex = sqlite3_column_text(stmt, 2);
            Contact *contact = [[Contact alloc] init];
            contact.contact_id =
            contact.name = [NSString stringWithUTF8String:(const char *)contact_name];
            [array addObject:contact];
        }
    }
    sqlite3_finalize(stmt);
    return array;
}
@end
